package com.cya.lotterysystem.controller;

import com.cya.lotterysystem.common.errcode.ControllerErrorCodeConstans;
import com.cya.lotterysystem.common.exception.ControllerException;
import com.cya.lotterysystem.common.pojo.CommonResult;
import com.cya.lotterysystem.common.utils.JacksonUtil;
import com.cya.lotterysystem.controller.param.ShortMessageLoginParam;
import com.cya.lotterysystem.controller.param.UserPasswordLoginParam;
import com.cya.lotterysystem.controller.param.UserRegisterParam;
import com.cya.lotterysystem.controller.reslut.BaseUserInfoResult;
import com.cya.lotterysystem.controller.reslut.UserLoginResult;
import com.cya.lotterysystem.controller.reslut.UserRegisterResult;
import com.cya.lotterysystem.dao.dataobject.UserDo;
import com.cya.lotterysystem.service.UserService;
import com.cya.lotterysystem.service.VerificationCodeService;
import com.cya.lotterysystem.service.dto.UserDTO;
import com.cya.lotterysystem.service.dto.UserLoginDTO;
import com.cya.lotterysystem.service.dto.UserRegisterDTO;
import com.cya.lotterysystem.service.enums.UserIdentityEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/10/28 16:07
 * @description：
 * @modified By：
 * @version:
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    private static final Logger logger= LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam param){
logger.info("userRegister UserRegisterParam:{}", JacksonUtil.writeValueAsString(param));
        UserRegisterDTO register = userService.register(param);
        return CommonResult.success(converToUserRegisterResult(register));
    }

    /**
     * 发送验证码服务
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/sendVerification")
    public CommonResult<String> sendVerification(String phoneNumber){

        logger.info("sendVerificationCode phoneNumber:{}",phoneNumber);

        verificationCodeService.sendVerificationCode(phoneNumber);
        String code=verificationCodeService.getVerificationCode(phoneNumber);
        return CommonResult.success(code);
    }

    /**
     * 将UserRegisterDTO类型数据转换为UserRegisterResult
     * @param register
     * @return
     */
    public UserRegisterResult converToUserRegisterResult(UserRegisterDTO register) {
        UserRegisterResult result=new UserRegisterResult();
        if (null==register){
            throw new ControllerException(ControllerErrorCodeConstans.REGISTER_ERROR);

        }
        result.setUserId(register.getUserId());
        return result;
    }

    /**
     * 密码登录
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public  CommonResult<UserLoginResult> userPasswordLogin(
           @Validated @RequestBody UserPasswordLoginParam param){

        logger.info("userPasswordLogin UserPasswordLoginParam:{}",JacksonUtil.writeValueAsString(param));


       UserLoginDTO userLoginDTO= userService.login(param);

       return CommonResult.success(converToUserLoginrResult(userLoginDTO));


    }

    private UserLoginResult converToUserLoginrResult(UserLoginDTO userLoginDTO) {
                if (userLoginDTO==null){
                    throw new ControllerException(ControllerErrorCodeConstans.LOGIN_ERROR);
                }
                UserLoginResult result=new UserLoginResult();
                result.setToken(userLoginDTO.getToken());

                result.setIdentity(userLoginDTO.getIdentity().name());
                return result;
    }

    /**
     * 验证码登陆方式
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public  CommonResult<UserLoginResult> shortMessageLogin(  @Validated @RequestBody ShortMessageLoginParam param){
        logger.info("userPasswordLogin UserPasswordLoginParam:{}"
                ,JacksonUtil.writeValueAsString(param));


        UserLoginDTO userLoginDTO= userService.login(param);

        return CommonResult.success(converToUserLoginrResult(userLoginDTO));


    }

    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity) {
            logger.info("findBaseUserInfo idemtity:{}",identity);

            List<UserDTO> userDTOList=userService.findUserInfo(
                    UserIdentityEnum.forName(identity));
            return CommonResult.success(converTOList(userDTOList));

        }

    /**
     * 将service层返回的数据转换成contrller层需要返回的数据格式
      * @param userDTOList
     * @return
     */
    private List<BaseUserInfoResult> converTOList(List<UserDTO> userDTOList) {
                if(CollectionUtils.isEmpty(userDTOList)){
                    return Arrays.asList();
                }
                return userDTOList.stream()
                        .map(userDTO -> {
                            BaseUserInfoResult baseUserInfoResult=new BaseUserInfoResult();
                            baseUserInfoResult.setUserId(userDTO.getUserId());
                            baseUserInfoResult.setUserName(userDTO.getUserName());
                            baseUserInfoResult.setIdentity(userDTO.getIdentity().name());
                            return baseUserInfoResult;
                        }).collect(Collectors.toList());
    }


}